package com.bit.demo.controller;

import com.bit.demo.model.MessageInfo;
import com.bit.demo.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
   // private List<MessageInfo> messageInfos = new ArrayList<>();

    @Autowired
    private MessageService messageService;

    @RequestMapping("/getList")
    public List<MessageInfo> getList() {
        log.info("查询所有列表");
        return messageService.getList();
    }
    @RequestMapping(value = "/publish", produces = "application/json")
    public String publish(@RequestBody MessageInfo messageInfo) {
        log.info("发布留言, messageInfo: {}", messageInfo);

        if(!StringUtils.hasLength(messageInfo.getFrom()) ||
         !StringUtils.hasLength(messageInfo.getTo()) ||
        !StringUtils.hasLength(messageInfo.getMessage())) {
            return "{\"ok\":0}";
        }
       try{
           Integer result = messageService.insertMessage(messageInfo);
           return result == 1?"{\"ok\":1}":"{\"ok\":0}";
       }catch(Exception e){
           log.error("发布留言失败", e);
           return "{\"ok\":0}";
       }
    }
}
